<template>
  <view class="warehouse-container">
    <!-- A. 页面头部 -->
    <view class="page-header">
      <text class="page-title">轧制作业</text>
    </view>

    <!-- B. 主信息区 -->
    <view class="plan-form-container">
      <view class="section-header">
        <text class="section-title">作业设定</text>
      </view>

      <view class="form-section">
        <view class="form-row">
          <view
            class="form-group"
            style="flex-direction: row; align-items: center"
          >
            <text
              class="form-label"
              style="margin-right: 20rpx; margin-bottom: 0"
              >生产工序</text
            >
            <picker
              mode="selector"
              :range="processOptions"
              range-key="text"
              :value="currentProcessIndex"
              @change="handleProcessChange"
              class="form-picker"
              style="flex: 1"
            >
              <view class="picker-content">
                <text>{{
                  currentProcess && currentProcess.processName
                    ? currentProcess.processName
                    : "请选择生产工序"
                }}</text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
          </view>
        </view>

        <view class="form-row">
          <view
            class="form-group"
            style="flex-direction: row; align-items: baseline; flex: 1"
          >
            <text class="form-label" style="margin-right: 10px">班别：</text>
            <text class="form-value">{{ workClass || "未设置" }}</text>
          </view>
          <view
            class="form-group"
            style="
              flex-direction: row;
              align-items: baseline;
              flex: 1;
              margin-left: 20px;
            "
          >
            <text class="form-label" style="margin-right: 10px">班次：</text>
            <text class="form-value">{{ workShift || "未设置" }}</text>
          </view>
        </view>

        <view class="form-row">
          <view class="form-group" style="flex: none; width: 100%">
            <text class="form-label">操作备注</text>
            <input
              type="text"
              class="form-input"
              placeholder="请输入操作备注"
              style="
                border: 1px solid #e0e0e0;
                border-radius: 6px;
                padding: 8px;
                background-color: #fafafa;
                resize: vertical;
                min-height: 60px;
                font-size: 14px;
                line-height: 1.4;
              "
              v-model.trim="formData.busMemo"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- C. 计划查询与作业记录TAB区域 -->
    <view class="plan-form-container">
      <view class="form-section">
        <view class="form-row">
          <view class="form-group" style="flex: none; width: 100%">
            <!-- 使用统一扫码输入组件 -->
            <ScanInput
              v-model="searchForm.searchCode"
              placeholder="1.请输入批次号"
              tip-text="支持扫描批次号"
              :loading="false"
              :on-scan-result="handleScanResult"
              :on-confirm="handleScanConfirm"
              ref="scanInputRef"
            />
          </view>
        </view>
        <!-- 出炉时间、停火时间选择器 -->
        <view class="form-row">
          <view class="form-group">
            <text class="form-label">出炉时间</text>
            <view style="display: flex; align-items: center; gap: 8px">
              <picker
                mode="multiSelector"
                :range="dateTimePickerRange"
                :value="batchEndPickerIndex"
                @change="handleBatchEndChange"
                class="form-picker"
                style="flex: 1"
              >
                <view class="picker-content">
                  <text>{{ formData.furnaceBatchOut || "出炉时间" }}</text>
                  <text class="picker-arrow">▼</text>
                </view>
              </picker>
              <button
                class="btn-select btn-sm"
                @click="setCurrentDateTime('furnaceBatchOut')"
              >
                确认
              </button>
            </view>
          </view>
          <view class="form-group">
            <text class="form-label">停火时间</text>
            <view style="display: flex; align-items: center; gap: 8px">
              <picker
                mode="multiSelector"
                :range="dateTimePickerRange"
                :value="furnaceEndPickerIndex"
                @change="handleFurnaceEndChange"
                class="form-picker"
                style="flex: 1"
              >
                <view class="picker-content">
                  <text>{{ formData.furnaceBatchEnd || "停火时间" }}</text>
                  <text class="picker-arrow">▼</text>
                </view>
              </picker>
              <button
                class="btn-select btn-sm"
                @click="setCurrentDateTime('furnaceBatchEnd')"
              >
                确认
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="plan-form-container">
      <!-- TAB页切换 -->
      <view class="tab-container">
        <view
          class="tab-item"
          :class="{ active: activeTab === 'plan' }"
          @click="activeTab = 'plan'"
        >
          2.计划设定
        </view>
        <view
          class="tab-item"
          :class="{ active: activeTab === 'operation' }"
          @click="activeTab = 'operation'"
        >
          3.作业记录
        </view>
      </view>

      <!-- 计划设定TAB内容 -->
      <view v-if="activeTab === 'plan'" class="tab-content">
        <!-- 查询条件 -->
        <view class="section-header">
          <text class="section-title">查询条件</text>
          <view class="time-filter-buttons">
            <button
              class="filter-btn"
              :class="{ active: planQueryData.dateType === 'today' }"
              @tap="changeDateFilter('today')"
            >
              今日
            </button>
            <button
              class="filter-btn"
              :class="{ active: planQueryData.dateType === 'yesterday' }"
              @tap="changeDateFilter('yesterday')"
            >
              昨日
            </button>
            <button
              class="filter-btn"
              :class="{ active: planQueryData.dateType === 'tomorrow' }"
              @tap="changeDateFilter('tomorrow')"
            >
              明日
            </button>
            <button
              class="filter-btn"
              :class="{ active: planQueryData.dateType === 'week' }"
              @tap="changeDateFilter('week')"
            >
              近7天
            </button>
          </view>
        </view>

        <!-- 汇总统计 -->
        <view class="section-header">
          <text class="section-title">汇总统计</text>
          <view class="statistics-info">
            <text class="stat-item">总计划量: {{ totalPlanWeight }} KG</text>
          </view>
        </view>

        <!-- 计划列表 -->
        <scroll-view class="table-scroll" scroll-y scroll-x>
          <view class="table-scroll-container">
            <view class="table-scroll-wrapper">
              <view class="table-content">
                <view class="table-row header">
                  <text class="table-cell">计划日期</text>
                  <text class="table-cell">钢种</text>
                  <text class="table-cell">规格</text>
                  <text class="table-cell">计划重量</text>
                  <text class="table-cell">操作</text>
                </view>
                <view
                  v-for="(plan, index) in planQueryData.planList"
                  :key="index"
                  class="table-row"
                  :class="{ selected: planQueryData.selectedPlan === plan }"
                  @click="selectPlan(plan)"
                >
                  <text class="table-cell" :title="plan.reserveVarchar3">{{
                    plan.reserveVarchar3
                  }}</text>
                  <text class="table-cell" :title="plan.steelGradeName">{{
                    plan.steelGradeName
                  }}</text>
                  <text class="table-cell" :title="plan.prodSpec">{{
                    plan.prodSpec
                  }}</text>
                  <text class="table-cell">{{ plan.planCount }}</text>
                  <view class="table-cell">
                    <button class="btn-select" @click.stop="selectPlan(plan)">
                      选择
                    </button>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 作业记录TAB内容 -->
      <view v-if="activeTab === 'operation'" class="tab-content">
        <!-- 产品下线内容 -->
        <view class="form-section">
          <view class="form-row">
            <view class="form-group">
              <text class="form-label">炉次号</text>
              <input
                type="text"
                class="form-input"
                placeholder="炉次号"
                v-model.trim="furnaceNoDisplay"
                :disabled="true"
                style="width: 100%"
              />
            </view>
          </view>
          <view class="form-row">
            <view class="form-group" style="flex: none; width: 100%">
              <text class="form-label">批次</text>
              <view style="display: flex; align-items: center; gap: 8px">
                <input
                  type="text"
                  class="form-input"
                  placeholder="请点击批次创建自动生成"
                  v-model.trim="formData.batchNo"
                  style="flex: 1"
                />
              </view>
              <view class="form-row" style="justify-content: space-around; margin-top: 10px;">
                <button 
                  class="btn-submit" 
                  @click="handleCreateBatch"
                  style="font-size: 30px; padding: 0px 24px; min-width: 300px;"
                >
                  批次创建
                </button>
                <button 
                  class="btn-submit" 
                  @click="handlePrintBatch"
                  style="font-size: 30px; padding: 0px 24px; min-width: 300px;"
                >
                  批次打印
                </button>
              </view>
            </view>
          </view>

          <view class="form-row">
            <view class="form-group">
              <text class="form-label">钢种</text>
              <input
                type="text"
                class="form-input"
                placeholder="钢种"
                v-model.trim="formData.steelGradeName"
              />
            </view>
            <view class="form-group">
              <text class="form-label">规格</text>
              <input
                type="text"
                class="form-input"
                placeholder="规格"
                v-model.trim="formData.prodSpec"
              />
            </view>
          </view>

          <view class="form-row">
            <view class="form-group">
              <text class="form-label">产出重量</text>
              <input
                type="digit"
                class="form-input"
                placeholder="请输入产出重量"
                v-model.number="formData.qmAmount"
                @input="validateNumber($event, formData, 'qmAmount')"
              />
            </view>
            <view class="form-group">
              <text class="form-label">产出支数</text>
              <input
                type="number"
                class="form-input"
                placeholder="请输入产出支数"
                v-model.number="formData.qmCount"
                @input="validateNumber($event, formData, 'qmCount')"
              />
            </view>
          </view>

          <view class="form-row">
            <view class="form-group" style="flex: none; width: 100%">
              <text class="form-label">操作备注</text>
              <input
                type="text"
                class="form-input"
                placeholder="请输入操作备注"
                style="
                  border: 1px solid #e0e0e0;
                  border-radius: 6px;
                  padding: 8px;
                  background-color: #fafafa;
                  resize: vertical;
                  min-height: 60px;
                  font-size: 14px;
                  line-height: 1.4;
                "
                v-model.trim="formData.busMemo"
              />
            </view>
          </view>

          <view class="form-row">
            <view class="form-group">
              <text class="form-label">废品支数</text>
              <input
                type="number"
                class="form-input"
                placeholder="请输入废品支数"
                v-model.number="formData.scrapCount"
                @input="validateNumber($event, formData, 'scrapCount')"
              />
            </view>
            <view class="form-group">
              <text class="form-label">废品重量</text>
              <input
                type="digit"
                class="form-input"
                placeholder="请输入废品重量"
                v-model.number="formData.scrapWg"
                @input="validateNumber($event, formData, 'scrapWg')"
              />
            </view>
          </view>

          <view class="form-row">
            <view class="form-group" style="flex: none; width: 100%">
              <text class="form-label">废品原因</text>
              <input
                type="text"
                class="form-input"
                placeholder="请输入废品原因"
                v-model.trim="formData.scrapReason"
              />
            </view>
          </view>

          <view class="form-row">
            <view class="form-group">
              <text class="form-label">开轧时间</text>
              <view style="display: flex; align-items: center; gap: 8px">
                <picker
                  mode="multiSelector"
                  :range="dateTimePickerRange"
                  :value="batchBeginPickerIndex"
                  @change="handleBatchBeginChange"
                  class="form-picker"
                  style="flex: 1"
                >
                  <view class="picker-content">
                    <text>{{ formData.batchBegin || "开轧时间" }}</text>
                    <text class="picker-arrow">▼</text>
                  </view>
                </picker>
                <button
                  class="btn-select btn-sm"
                  @click="setCurrentDateTime('batchBegin')"
                >
                  确认
                </button>
              </view>
            </view>
            <view class="form-group">
              <text class="form-label">终轧时间</text>
              <view style="display: flex; align-items: center; gap: 8px">
                <picker
                  mode="multiSelector"
                  :range="dateTimePickerRange"
                  :value="batchEndPickerIndex"
                  @change="handleBatchEndChange"
                  class="form-picker"
                  style="flex: 1"
                >
                  <view class="picker-content">
                    <text>{{ formData.furnaceBatchOut || "终轧时间" }}</text>
                    <text class="picker-arrow">▼</text>
                  </view>
                </picker>
                <button
                  class="btn-select btn-sm"
                  @click="setCurrentDateTime('furnaceBatchOut')"
                >
                  确认
                </button>
              </view>
            </view>
          </view>
          <!-- 退火入炉时间、退火出炉时间 -->
          <view class="form-row">
            <view class="form-group">
              <text class="form-label">退火入炉时间</text>
              <view style="display: flex; align-items: center; gap: 8px">
                <picker
                  mode="multiSelector"
                  :range="dateTimePickerRange"
                  :value="tFurnaceBatchBeginPickerIndex"
                  @change="handleTFurnaceBatchBeginChange"
                  class="form-picker"
                  style="flex: 1"
                >
                  <view class="picker-content">
                    <text>{{
                      formData.tFurnaceBatchBegin || "退火入炉时间"
                    }}</text>
                    <text class="picker-arrow">▼</text>
                  </view>
                </picker>
                <button
                  class="btn-select btn-sm"
                  @click="setCurrentDateTime('tFurnaceBatchBegin')"
                >
                  确认
                </button>
              </view>
            </view>
            <view class="form-group">
              <text class="form-label">退火出炉时间</text>
              <view style="display: flex; align-items: center; gap: 8px">
                <picker
                  mode="multiSelector"
                  :range="dateTimePickerRange"
                  :value="tFurnaceBatchEndPickerIndex"
                  @change="handleTFurnaceBatchEndChange"
                  class="form-picker"
                  style="flex: 1"
                >
                  <view class="picker-content">
                    <text>{{
                      formData.tFurnaceBatchEnd || "退火出炉时间"
                    }}</text>
                    <text class="picker-arrow">▼</text>
                  </view>
                </picker>
                <button
                  class="btn-select btn-sm"
                  @click="setCurrentDateTime('tFurnaceBatchEnd')"
                >
                  确认
                </button>
              </view>
            </view>
          </view>
        </view>

        <!-- D. 按钮操作区 -->
        <view class="button-row">
          <button class="btn-reset" @click="handleReset">重置</button>
          <button class="btn-submit" @click="handleOffline">4. 保存</button>
        </view>
      </view>
    </view>

    <!-- 退火炉记录选择表格弹窗 -->
    <RecordSelectionModal
      :visible="showRecordTable"
      title="选择退火炉记录"
      :records="furnaceRecords"
      @close="closeRecordTable"
      @confirm="handleRecordSelectionConfirm"
    />
  </view>
</template>

<script>
// 导入API方法
import { getProcessOptions } from "@/api/md/process";
import { LzProdStockRealApi } from "@/api/warehouse/lzprodstockreal";
import { ZgRecordRollApi } from "@/api/lz/zgrecordroll";
import { ZgRecordFurnaceApi } from "@/api/lz/zgrecordfurnace";

import { PlanLzApi } from "@/api/pp/planlz";

// 导入统一扫码输入组件
import ScanInput from "@/components/ScanInput";

// 导入记录选择弹窗组件
import RecordSelectionModal from "./components/RecordSelectionModal";

import { dateHelperApi } from "@/pages/smart/warehouse/utils/date-helper";
import { pdaScanApi } from "@/pages/smart/pdaScan";
export default {
  name: "StockIn",
  mixins: [pdaScanApi],
  components: {
    ScanInput,
    RecordSelectionModal,
  },

  data() {
    return {
      // 表单数据
      formData: {
        currentDate: dateHelperApi.getCurrentDate(),
        processCode: "",
        processName: "",
        // 基础字段
        furnaceNo: "", // 炉次号
        operationMemo: "", // 操作备注
        workStaff: "", // 配渣工
        // 投料作业字段
        costWg: "", // 钢棒重量
        costCount: "", // 钢棒支数
        // 产出作业字段
        batchNo: "", // 批次号
        steelGradeName: "", // 钢种
        prodSpec: "", // 规格
        qmAmount: "", // 产出重量
        qmCount: "", // 产出支数
        scrapCount: "", // 废品支数
        scrapWg: "", // 废品重量
        scrapReason: "", // 废品原因
        // 时间相关字段
        batchBegin: "", // 开轧时间
        batchEnd: "", // 终轧时间
        furnaceBatchOut: "", // 加热炉出炉时间
        furnaceBatchEnd: "", // 加热炉停火时间
        tFurnaceBatchBegin: "", // 退火入炉时间
        tFurnaceBatchEnd: "", // 退火出炉时间

        planNo: "", // 计划号
        materialCode: "", // 物料编码
        materialName: "", // 物料名称
      },
      // 扫码查询表单
      searchForm: {
        searchCode: "", // 扫码内容
      },
      // 扫码加载状态（已取消）
      scanLoading: false,

      // 当前工序信息
      currentProcess: {
        processCode: "",
        processName: "请选择生产工序",
      },
      // 班次班组信息
      workShift: "", // 班次
      workClass: "", // 班组

      // 工序选项列表
      processOptions: [],
      // 当前工序索引
      currentProcessIndex: -1,
      // 炉次信息表格数据
      furnaceTable: [],
      // 炉次号显示
      furnaceNoDisplay: "",
      // 表格是否可编辑
      isTableEditable: true,
      // 转料方式选项
      transferMethods: ["天车", "叉车", "输送带", "其他"],

      // 计划查询相关数据
      planQueryData: {
        dateType: "today", // 日期筛选类型
        planList: [], // 计划列表
        selectedPlan: null, // 选中的计划
      },

      // TAB切换状态
      activeTab: "plan", // 当前激活的标签页: plan-计划设定, record-作业记录

      // 时间选择器索引
      batchBeginPickerIndex: [5, 0, 0, 0, 0, 0], // 入炉时间选择器索引
      batchEndPickerIndex: [5, 0, 0, 0, 0, 0], // 终轧时间选择器索引
      furnaceBeginPickerIndex: [5, 0, 0, 0, 0, 0], // 点火时间选择器索引
      furnaceEndPickerIndex: [5, 0, 0, 0, 0, 0], // 停火时间选择器索引
      tFurnaceBatchBeginPickerIndex: [5, 0, 0, 0, 0, 0], // 退火入炉时间选择器索引
      tFurnaceBatchEndPickerIndex: [5, 0, 0, 0, 0, 0], // 退火出炉时间选择器索引

      // 退火炉记录查询和选择相关数据
      furnaceRecords: [], // 查询到的退火炉记录列表
      selectedRecords: [], // 用户选中的记录ID数组
      showRecordTable: false, // 控制表格显示状态
    };
  },
  computed: {
    // 日期工具命名空间（供模板使用）
    dateHelperApi() {
      return dateHelperApi;
    },

    // 总计划重量
    totalPlanWeight() {
      if (
        !this.planQueryData.planList ||
        this.planQueryData.planList.length === 0
      ) {
        return 0;
      }
      return this.planQueryData.planList.reduce((total, plan) => {
        return total + (Number(plan.planCount) || 0);
      }, 0);
    },

    // 日期时间选择器的选项范围
    dateTimePickerRange() {
      const years = [];
      const months = [];
      const days = [];
      const hours = [];
      const minutes = [];
      const seconds = [];

      // 年份：2020-2030
      for (let i = 2020; i <= 2030; i++) {
        years.push(String(i));
      }

      // 月份：1-12
      for (let i = 1; i <= 12; i++) {
        months.push(String(i).padStart(2, "0"));
      }

      // 日期：1-31（实际使用时需要根据年月动态计算）
      for (let i = 1; i <= 31; i++) {
        days.push(String(i).padStart(2, "0"));
      }

      // 小时：0-23
      for (let i = 0; i < 24; i++) {
        hours.push(String(i).padStart(2, "0"));
      }

      // 分钟：0-59
      for (let i = 0; i < 60; i++) {
        minutes.push(String(i).padStart(2, "0"));
      }

      // 秒：0-59
      for (let i = 0; i < 60; i++) {
        seconds.push(String(i).padStart(2, "0"));
      }

      return [years, months, days, hours, minutes, seconds];
    },
  },
  async onLoad() {
    await this.loadProcessOptions(); // 加载工序选项
    this.loadCurrentProcess(); // 加载当前工序
    // 初始化PDA打印模块（来自mixin）
    this.initScanModule();

    // 页面加载时默认查询今日的计划
    await this.loadPlanList();
  },
  beforeDestroy() {
    // 停止PDA扫码，释放资源（来自mixin）
    this.stopPdaScan();
  },
  methods: {
    // 日期筛选切换
    changeDateFilter(dateType) {
      this.planQueryData.dateType = dateType;
      this.loadPlanList();
    },

    // 加载计划列表
    async loadPlanList(loadMore = false) {
      try {
        if (!loadMore) {
          this.planQueryData.pageNum = 1;
          this.planQueryData.hasMore = true;
        }

        this.planQueryData.loading = true;

        // 根据日期类型获取时间范围
        let timeRange = {};

        // 使用通用的updateDateRange函数获取时间范围
        const result = dateHelperApi.updateDateRange(
          this.planQueryData.dateType,
          {
            callback: ({ startDate, endDate }) => {
              timeRange = { startDate, endDate };
            },
          }
        );

        // 调用计划查询接口
        const params = {
          pageNum: this.planQueryData.pageNum,
          pageSize: this.planQueryData.pageSize,
          reserveVarchar2: "轧钢",
        };

        //只有在时间范围有效时才添加时间参数 - 使用数组格式传递到reserveVarchar3字段
        if (timeRange.startDate && timeRange.endDate) {
          // dateHelperApi.updateDateRange返回的是YYYY-MM-DD HH:mm:ss格式
          // 格式化为YYYY-MM-DD格式，去掉时分秒
          const startDateFormatted = timeRange.startDate.split(" ")[0];
          const endDateFormatted = timeRange.endDate.split(" ")[0];
          params.reserveVarchar3 = [startDateFormatted, endDateFormatted];
        }

        const response = await PlanLzApi.getPlanLzDetailPage(params);

        if (response.code === 0 && response.data && response.data.list) {
          // 将查询结果转换为计划列表格式
          const newPlans = response.data.list.map((item) => ({
            planNo: item.planDetailNo,
            steelGradeName: item.steelGradeName || "",
            prodSpec: item.prodSpec || "",
            planCount: item.planCount ? `${item.planCount}KG` : "0KG",
            reserveVarchar3: item.reserveVarchar3 || "",
            materialCode: item.materialCode || "",
            materialName: item.materialName || "",
          }));

          //赋值到planQueryData.planList
          if (loadMore) {
            this.planQueryData.planList.push(...newPlans);
          } else {
            this.planQueryData.planList = newPlans;
          }

          if (this.planQueryData.planList.length === 0) {
            uni.showToast({
              title: "未查询到计划信息",
              icon: "none",
            });
          } else if (!loadMore) {
            uni.showToast({
              title: `查询到${this.planQueryData.planList.length}条计划信息`,
              icon: "success",
            });
          }
        } else {
          this.planQueryData.planList = [];
          this.planQueryData.hasMore = false;
          uni.showToast({
            title: "查询计划信息失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("查询计划信息失败:", error);
        this.planQueryData.planList = [];
        this.planQueryData.hasMore = false;
        uni.showToast({
          title: "查询计划信息失败",
          icon: "none",
        });
      } finally {
        this.planQueryData.loading = false;
      }
    },

    // 选择计划
    selectPlan(plan) {
      this.planQueryData.selectedPlan = plan;

      // 检查钢种一致性
      if (
        this.formData.steelGradeName &&
        this.formData.steelGradeName !== plan.steelGradeName
      ) {
        uni.showModal({
          title: "钢种不一致",
          content: `当前表单钢种为${this.formData.steelGradeName}，计划钢种为${plan.steelGradeName}，是否继续选择？`,
          success: (res) => {
            if (res.confirm) {
              this.doSelectPlan(plan);
            }
          },
        });
      } else {
        this.doSelectPlan(plan);
      }
    },

    // 执行计划选择
    doSelectPlan(plan) {
      // 将计划数据赋值到form表单
      this.formData.planNo = plan.planNo;
      this.formData.materialCode = plan.materialCode;
      this.formData.materialName = plan.materialName;
      this.formData.steelGradeName = plan.steelGradeName;
      this.formData.prodSpec = plan.prodSpec;

      // 切换到作业记录TAB
      this.activeTab = "operation";

      uni.showToast({
        title: "已选择计划",
        icon: "success",
      });
    },

    // 扫码结果处理
    handleScanResult(result) {
      // 预处理扫码结果
      if (result && result.length > 0) {
        this.searchForm.searchCode = result;
        this.handleScanConfirm();
      }
    },

    // 扫码确认查询
    async handleScanConfirm() {
      if (!this.searchForm.searchCode.trim()) {
        uni.showToast({
          title: "请输入批次号",
          icon: "none",
        });
        return;
      }

      try {
        // 根据扫码内容判断查询类型并调用相应接口
        const searchCode = this.searchForm.searchCode.trim();

        // 调用批次号查询接口
        const params = {
          batchNo: searchCode,
          pageNum: 1,
          processName: "提纯",
          pageSize: 100,
        };

        const response = await ZgRecordFurnaceApi.getZgRecordFurnacePage(
          params
        );

        if (response.code === 0) {
          //将查询结果的第一行赋值给form相关字段
          if (
            response.data &&
            response.data.list &&
            response.data.list.length > 0
          ) {
            const firstItem = response.data.list[0];
            this.formData.batchNo = firstItem.batchNo || "";
            //炉号
            this.formData.furnaceNo = firstItem.furnaceNo || "";
            this.furnaceNoDisplay = firstItem.furnaceNo || "";
            //计划号
            // this.formData.planNo = firstItem.planNo || "";
            this.formData.steelGradeName = firstItem.steelGradeName || "";
            this.formData.prodSpec = firstItem.prodSpec || "";
            // this.formData.qmAmount = firstItem.qmAmount || 0;
            // this.formData.qmCount = firstItem.qmCount || 0;
            // this.formData.materialCode = firstItem.materialCode || "";
            // this.formData.materialName = firstItem.materialName || "";
            this.formData.busMemo = firstItem.busMemo || "";
            
            // 处理时间戳字段，转换为日期时间字符串
            // 出炉时间（对应furnaceBatchOut）
            if (firstItem.batchEnd) {
              this.formData.furnaceBatchOut = this.timestampToDateTimeString(firstItem.batchEnd);
              // 更新picker索引
              if (this.formData.furnaceBatchOut) {
                this.batchEndPickerIndex = this.dateTimeStringToIndex(this.formData.furnaceBatchOut);
              }
            }
            
            // 停火时间（对应furnaceBatchEnd）
            if (firstItem.furnaceEnd) {
              this.formData.furnaceBatchEnd = this.timestampToDateTimeString(firstItem.furnaceEnd);
              // 更新picker索引
              if (this.formData.furnaceBatchEnd) {
                this.furnaceEndPickerIndex = this.dateTimeStringToIndex(this.formData.furnaceBatchEnd);
              }
            }
            
            // 开轧时间（对应batchBegin）
            if (firstItem.batchBegin) {
              this.formData.batchBegin = this.timestampToDateTimeString(firstItem.batchBegin);
              // 更新picker索引
              if (this.formData.batchBegin) {
                this.batchBeginPickerIndex = this.dateTimeStringToIndex(this.formData.batchBegin);
              }
            } else if (this.formData.furnaceBatchOut) {
              // 如果开轧时间为空，但出炉时间有值，则使用出炉时间作为开轧时间
              this.formData.batchBegin = this.formData.furnaceBatchOut;
              this.batchBeginPickerIndex = this.dateTimeStringToIndex(this.formData.batchBegin);
            }
            
            // 查询轧制记录，获取产出重量、产出支数和操作备注
            try {
              const rollParams = {
                batchNo: searchCode,
                pageNo: 1,
                pageSize: 100,
              };
              
              const rollResponse = await ZgRecordRollApi.getZgRecordRollPage(rollParams);
              
              if (rollResponse.code === 0 && 
                  rollResponse.data && 
                  rollResponse.data.list && 
                  rollResponse.data.list.length > 0) {
                // 取第一条记录的数据（如果有多条，取最新的或第一条）
                const rollItem = rollResponse.data.list[0];
                
                // 填充产出重量（qmAmount）- 如果有值则覆盖
                if (rollItem.qmAmount !== null && rollItem.qmAmount !== undefined) {
                  this.formData.qmAmount = Number(rollItem.qmAmount) || 0;
                }
                
                // 填充产出支数（qmCount）- 如果有值则覆盖
                if (rollItem.qmCount !== null && rollItem.qmCount !== undefined) {
                  this.formData.qmCount = Number(rollItem.qmCount) || 0;
                }
                
                // 填充操作备注（优先使用busMemo，如果没有则使用recordMemo）- 如果有值则覆盖
                if (rollItem.busMemo) {
                  this.formData.busMemo = rollItem.busMemo;
                } else if (rollItem.recordMemo) {
                  this.formData.busMemo = rollItem.recordMemo;
                }
              }
            } catch (rollError) {
              console.error("查询轧制记录失败:", rollError);
              // 查询轧制记录失败不影响主流程，只记录错误
              // 产出重量、产出支数和操作备注保持为空或原有值
            }
            
            uni.showToast({
              title: `查询成功`,
              icon: "success",
            });
          }
        }
      } catch (error) {
        console.error("查询批次号信息失败:", error);
        this.formData.batchNo = "";
        this.formData.steelGradeName = "";
        this.formData.prodSpec = "";
        this.formData.planCount = 0;
        this.formData.materialCode = "";
        this.formData.materialName = "";
        uni.showToast({
          title: "查询批次号信息失败",
          icon: "none",
        });
      }
    },

    /* 加载当前工序 */
    loadCurrentProcess() {
      // 尝试从用户配置中加载缓存的工序信息
      const userData = this.$store.state.user;
      const userConfig = userData.userConfig || {};
      if (userData && userData.userConfig) {
        const userConfig = userData.userConfig;
        // 从缓存中加载工序信息
        if (userConfig.processNo && userConfig.processName) {
          this.currentProcess = {
            processCode: userConfig.processNo,
            processName: userConfig.processName,
          };
          this.formData.processCode = userConfig.processNo;
          this.formData.processName = userConfig.processName;

          // 加载班次班组信息
          this.workShift = userConfig.workShift || "";
          this.workClass = userConfig.workClass || "";

          // 在工序选项中找到对应的索引
          const processIndex = this.processOptions.findIndex(
            (item) => item.value === userConfig.processNo
          );
          if (processIndex !== -1) {
            this.currentProcessIndex = processIndex;
          }
          return;
        }
      }

      // 如果没有缓存或缓存无效，默认选择第一个工序
      if (this.processOptions.length > 0) {
        this.currentProcess = {
          processCode: this.processOptions[0].value,
          processName: this.processOptions[0].text,
        };
        this.formData.processCode = this.currentProcess.processCode;
        this.formData.processName = this.currentProcess.processName;
        this.currentProcessIndex = 0;
      }
    },

    // 加载工序选项
    async loadProcessOptions() {
      try {
        const options = await getProcessOptions();
        this.processOptions = options;
        console.log("生产工序选项加载成功:", this.processOptions);
      } catch (error) {
        // 静默处理错误
        console.error("加载工序选项失败:", error);
        this.processOptions = [];
      }
    },

    /* 处理工序选择变化 */
    handleProcessChange(e) {
      const index = e.detail.value;
      this.currentProcessIndex = index;
      const selectedProcess = this.processOptions[index];
      if (selectedProcess) {
        this.currentProcess = {
          processCode: selectedProcess.value,
          processName: selectedProcess.text,
        };
        this.formData.processCode = selectedProcess.value;
        this.formData.processName = selectedProcess.text;
      }
    },

    // 打印测试
    async testPdaPrint() {
      try {
        console.log("开始打印测试...");

        const result = this.pdaPrint(
          "B20251019",
          "测试备注1",
          "备注2",
          "备注3"
        );

        if (result) {
          this.$modal.alert({
            content: "打印成功",
            title: "提示",
          });
        } else {
          this.$modal.alert({
            content: "打印失败，请检查打印机状态",
            title: "错误",
          });
        }
      } catch (error) {
        console.error("打印测试异常:", error);
        this.$modal.alert({
          content: "打印测试异常：" + error.message,
          title: "错误",
        });
      }
    },

    // 批次查询
    async handleBatchQuery() {
      if (!this.formData.batchNo) {
        uni.showToast({
          title: "请输入批次号",
          icon: "none",
        });
        return;
      }

      try {
        // 显示加载中
        uni.showLoading({
          title: "查询中...",
        });

        // 调用轧制记录查询API
        const params = {
          batchNo: this.formData.batchNo,
          pageNo: 1,
          pageSize: 50, // 批量查询显示更多数据
        };

        const response = await ZgRecordRollApi.getZgRecordRollPage(params);

        uni.hideLoading();

        if (response.code === 0) {
          // 将分页查询返回的第一行数据分别赋值给formData的字段中
          if (
            response.data &&
            response.data.list &&
            response.data.list.length > 0
          ) {
            const firstRow = response.data.list[0];

            // 填充基本信息
            this.formData.furnaceNo = firstRow.furnaceNo || "";
            this.formData.batchNo = firstRow.batchNo || "";
            this.furnaceNoDisplay = firstRow.furnaceNo || "";
            this.formData.steelGradeName = firstRow.steelGradeName || "";
            this.formData.prodSpec = firstRow.prodSpec || "";
            this.formData.planNo = firstRow.planNo || "";
            this.formData.materialCode = firstRow.materialCode || "";
            this.formData.materialName = firstRow.materialName || "";

            // 填充产出重量和产出支数
            if (firstRow.qmAmount !== null && firstRow.qmAmount !== undefined) {
              this.formData.qmAmount = Number(firstRow.qmAmount) || 0;
            }
            if (firstRow.qmCount !== null && firstRow.qmCount !== undefined) {
              this.formData.qmCount = Number(firstRow.qmCount) || 0;
            }

            // 填充操作备注（优先使用busMemo，如果没有则使用recordMemo）
            if (firstRow.busMemo) {
              this.formData.busMemo = firstRow.busMemo;
            } else if (firstRow.recordMemo) {
              this.formData.busMemo = firstRow.recordMemo;
            }

            // 处理时间戳字段，转换为日期时间字符串
            // 开轧时间（batchBegin）
            if (firstRow.batchBegin) {
              this.formData.batchBegin = this.timestampToDateTimeString(firstRow.batchBegin);
              if (this.formData.batchBegin) {
                this.batchBeginPickerIndex = this.dateTimeStringToIndex(this.formData.batchBegin);
              }
            }

            // 终轧时间（batchEnd，对应furnaceBatchOut）
            if (firstRow.batchEnd) {
              this.formData.furnaceBatchOut = this.timestampToDateTimeString(firstRow.batchEnd);
              if (this.formData.furnaceBatchOut) {
                this.batchEndPickerIndex = this.dateTimeStringToIndex(this.formData.furnaceBatchOut);
              }
            }

            // 如果开轧时间为空，但终轧时间有值，则使用终轧时间作为开轧时间
            if (!this.formData.batchBegin && this.formData.furnaceBatchOut) {
              this.formData.batchBegin = this.formData.furnaceBatchOut;
              this.batchBeginPickerIndex = this.dateTimeStringToIndex(this.formData.batchBegin);
            }

            // 退火入炉时间（reserveVarchar1）
            if (firstRow.reserveVarchar1) {
              this.formData.tFurnaceBatchBegin = this.timestampToDateTimeString(firstRow.reserveVarchar1);
              if (this.formData.tFurnaceBatchBegin) {
                this.tFurnaceBatchBeginPickerIndex = this.dateTimeStringToIndex(this.formData.tFurnaceBatchBegin);
              }
            }

            // 退火出炉时间（reserveVarchar2）
            if (firstRow.reserveVarchar2) {
              this.formData.tFurnaceBatchEnd = this.timestampToDateTimeString(firstRow.reserveVarchar2);
              if (this.formData.tFurnaceBatchEnd) {
                this.tFurnaceBatchEndPickerIndex = this.dateTimeStringToIndex(this.formData.tFurnaceBatchEnd);
              }
            }

            uni.showToast({
              title: `查询到${response.data.list.length}条记录`,
              icon: "success",
            });
          } else {
            uni.showToast({
              title: "未查询到批次信息",
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: response.msg || "查询失败",
            icon: "none",
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error("批次查询失败:", error);
        uni.showToast({
          title: "查询失败，请重试",
          icon: "none",
        });
      }
    },

    // PDA打印方法
    pdaPrint(batchNo, spec, printTime) {
      try {
        // 调用原生打印方法
        const result = this.handlePdaPrint(batchNo, spec, printTime);
        return result;
      } catch (error) {
        console.error("PDA打印失败:", error);
        return false;
      }
    },

    // 批次创建
    async handleCreateBatch() {
      // 校验是否存在炉次号
      if (!this.formData.furnaceNo) {
        uni.showToast({
          title: "请先扫码查询炉次号",
          icon: "none",
        });
        return;
      }

      try {
        uni.showLoading({
          title: "生成批次号...",
        });

        const furnaceNo = this.formData.furnaceNo;
        let baseBatchNo = this.formData.batchNo || "";

        // 1. 如果没有当前批次号，查询该炉号下已有的最大批次号
        if (!baseBatchNo || !baseBatchNo.trim()) {
          const queryParams = {
            furnaceNo: furnaceNo,
            pageNo: 1,
            pageSize: 100,
          };

          const queryResponse = await ZgRecordRollApi.getZgRecordRollPage(queryParams);

          // 找出该炉号下已有的最大批次号
          let maxBatchNo = null;
          if (queryResponse.code === 0 && queryResponse.data && queryResponse.data.list) {
            queryResponse.data.list.forEach((item) => {
              if (item.batchNo && item.furnaceNo === furnaceNo && item.batchNo.startsWith(furnaceNo)) {
                const suffix = item.batchNo.substring(furnaceNo.length);
                // 如果后缀是A-Z或AA-ZZ格式
                if (/^[A-Z]$/.test(suffix) || /^[A-Z][A-Z]$/.test(suffix)) {
                  if (!maxBatchNo || item.batchNo > maxBatchNo) {
                    maxBatchNo = item.batchNo;
                  }
                }
              }
            });
          }

          // 如果找到已有批次号，使用它作为基础；否则使用炉号+A作为第一个批次号
          if (maxBatchNo) {
            baseBatchNo = maxBatchNo;
          } else {
            baseBatchNo = furnaceNo + "A";
          }
        }

        // 2. 在基础批次号后追加一个字母，生成新批次号
        let newBatchNo = null;

        if (baseBatchNo.startsWith(furnaceNo)) {
          const suffix = baseBatchNo.substring(furnaceNo.length);

          // 如果后缀只有一个字母（如 A），则追加 A，变成 AA
          if (/^[A-Z]$/.test(suffix)) {
            newBatchNo = baseBatchNo + "A";
          }
          // 如果后缀已经是两个字母（如 AA），则找到下一个未使用的第二个字母
          else if (/^[A-Z][A-Z]$/.test(suffix)) {
            const firstLetter = suffix.charAt(0);
            const secondLetter = suffix.charAt(1);

            // 查询该炉号下所有已使用的批次号，找出相同第一个字母的所有第二个字母
            const queryParams = {
              furnaceNo: furnaceNo,
              pageNo: 1,
              pageSize: 100,
            };

            const queryResponse = await ZgRecordRollApi.getZgRecordRollPage(queryParams);

            // 提取已使用的第二个字母
            const usedSecondLetters = new Set();
            if (queryResponse.code === 0 && queryResponse.data && queryResponse.data.list) {
              queryResponse.data.list.forEach((item) => {
                if (item.batchNo && item.furnaceNo === furnaceNo) {
                  const batchNo = item.batchNo;
                  if (batchNo.startsWith(furnaceNo)) {
                    const itemSuffix = batchNo.substring(furnaceNo.length);
                    // 如果是两个字母，且第一个字母相同
                    if (/^[A-Z][A-Z]$/.test(itemSuffix) && itemSuffix.charAt(0) === firstLetter) {
                      usedSecondLetters.add(itemSuffix.charAt(1));
                    }
                  }
                }
              });
            }

            // 从当前第二个字母的下一个开始，找出第一个未使用的字母
            let nextSecondLetter = null;
            const currentSecondCode = secondLetter.charCodeAt(0);
            for (let c = currentSecondCode + 1; c <= 'Z'.charCodeAt(0); c++) {
              const letter = String.fromCharCode(c);
              if (!usedSecondLetters.has(letter)) {
                nextSecondLetter = letter;
                break;
              }
            }

            // 如果当前字母后面都用完了，从A开始找
            if (!nextSecondLetter) {
              for (let c = 'A'.charCodeAt(0); c <= 'Z'.charCodeAt(0); c++) {
                const letter = String.fromCharCode(c);
                if (!usedSecondLetters.has(letter)) {
                  nextSecondLetter = letter;
                  break;
                }
              }
            }

            if (nextSecondLetter) {
              newBatchNo = furnaceNo + firstLetter + nextSecondLetter;
            } else {
              uni.hideLoading();
              uni.showToast({
                title: `该批次号${baseBatchNo}的第二个字母A-Z已全部使用`,
                icon: "none",
                duration: 3000,
              });
              return;
            }
          } else {
            // 如果格式不符合预期，默认使用炉号+AA
            newBatchNo = furnaceNo + "AA";
          }
        } else {
          // 如果批次号格式不符合，默认使用炉号+AA
          newBatchNo = furnaceNo + "AA";
        }

        // 3. 校验新批次号是否已存在（防止重复）
        const checkParams = {
          furnaceNo: furnaceNo,
          batchNo: newBatchNo,
          pageNo: 1,
          pageSize: 1,
        };

        const checkResponse = await ZgRecordRollApi.getZgRecordRollPage(checkParams);
        if (checkResponse.code === 0 && checkResponse.data && checkResponse.data.list && checkResponse.data.list.length > 0) {
          uni.hideLoading();
          uni.showToast({
            title: `批次号${newBatchNo}已存在，请重试`,
            icon: "none",
            duration: 3000,
          });
          return;
        }

        uni.hideLoading();

        // 4. 将生成的批次号设置到表单中（不插入数据库）
        this.formData.batchNo = newBatchNo;

        uni.showToast({
          title: `批次号已生成：${newBatchNo}`,
          icon: "success",
          duration: 2000,
        });
      } catch (error) {
        uni.hideLoading();
        console.error("批次号生成失败:", error);
        uni.showToast({
          title: "批次号生成失败，请重试",
          icon: "none",
        });
      }
    },

    // 批次打印
    async handlePrintBatch() {
      if (!this.formData.batchNo) {
        uni.showToast({
          title: "请先创建批次",
          icon: "none",
        });
        return;
      }

      try {
        console.log("批次打印参数:", {
          batchNo: this.formData.batchNo,
          steelGradeName: this.formData.steelGradeName,
          printTime: dateHelperApi.getCurrentDate(),
        });

        // 调用PDA打印接口
        const printResult = this.pdaPrint(
          this.formData.batchNo, // 批次号
          this.formData.steelGradeName + "/" + this.formData.prodSpec || "", // 规格
          dateHelperApi.getCurrentDate() // 打印时间
        );

        if (printResult) {
          uni.showToast({
            title: "批次打印成功",
            icon: "success",
          });
        } else {
          uni.showToast({
            title: "批次打印失败，请检查设备",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("批次打印失败:", error);
        uni.showToast({
          title: "批次打印失败，请重试",
          icon: "none",
        });
      }
    },

    // 表格滚动到底部加载更多
    onReachBottom() {
      // 数据加载功能已取消
    },

    // 数字验证
    validateNumber(event, obj, field) {
      const value = parseFloat(event.detail.value);
      if (isNaN(value) || value < 0) {
        obj[field] = "";
        uni.showToast({
          title: "请输入有效的数字",
          icon: "none",
        });
      } else {
        obj[field] = value;
      }
    },

    // 设置当前时间
    setCurrentTime(field) {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");
      this.formData[
        field
      ] = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 设置当前日期时间（用于multiSelector模式）
    setCurrentDateTime(field) {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");
      this.formData[
        field
      ] = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

      // 更新对应的picker索引
      const yearIndex = year - 2020; // 与时间选择器range定义保持一致
      const monthIndex = now.getMonth();
      const dayIndex = now.getDate() - 1;
      const hourIndex = now.getHours();
      const minuteIndex = now.getMinutes();
      const secondIndex = now.getSeconds();

      if (field === "batchBegin") {
        this.batchBeginPickerIndex = [
          yearIndex,
          monthIndex,
          dayIndex,
          hourIndex,
          minuteIndex,
          secondIndex,
        ];
      } else if (field === "batchEnd" || field === "furnaceBatchOut") {
        this.batchEndPickerIndex = [
          yearIndex,
          monthIndex,
          dayIndex,
          hourIndex,
          minuteIndex,
          secondIndex,
        ];
        
        // 如果设置的是出炉时间，且开轧时间为空，则默认将开轧时间设置为出炉时间
        if (field === "furnaceBatchOut" && !this.formData.batchBegin) {
          this.formData.batchBegin = this.formData.furnaceBatchOut;
          this.batchBeginPickerIndex = [
            yearIndex,
            monthIndex,
            dayIndex,
            hourIndex,
            minuteIndex,
            secondIndex,
          ];
        }
      } else if (field === "furnaceEnd" || field === "furnaceBatchEnd") {
        this.furnaceEndPickerIndex = [
          yearIndex,
          monthIndex,
          dayIndex,
          hourIndex,
          minuteIndex,
          secondIndex,
        ];
      }
      //增加退火炉的时间选择
      else if (field === "tFurnaceBatchBegin") {
        this.tFurnaceBatchBeginPickerIndex = [
          yearIndex,
          monthIndex,
          dayIndex,
          hourIndex,
          minuteIndex,
          secondIndex,
        ];
      } else if (field === "tFurnaceBatchEnd") {
        this.tFurnaceBatchEndPickerIndex = [
          yearIndex,
          monthIndex,
          dayIndex,
          hourIndex,
          minuteIndex,
          secondIndex,
        ];
      }

      // 如果是退火炉时间字段，触发弹出框
      if (field === "tFurnaceBatchBegin" || field === "tFurnaceBatchEnd") {
        console.log(
          "annealing furnace time:",
          this.formData.tFurnaceBatchBegin,
          this.formData.tFurnaceBatchEnd
        );
        this.updateTFurnaceOut();
      }
      
      // 如果是出炉时间或停火时间字段，触发保存
      if (field === "furnaceBatchOut" || field === "furnaceBatchEnd") {
        this.updateFurnaceOut();
      }
    },
    async updateFurnaceOut() {
      // 调用更新加热炉出炉的方法
      // 构建下线数据
      // 判断批次号是否为空
      if (!this.formData.batchNo) {
        uni.showToast({
          title: "请输入批次号",
          icon: "none",
        });
        return;
      }
      
      // 判断出炉时间和停火时间是否至少有一个
      if (!this.formData.furnaceBatchOut && !this.formData.furnaceBatchEnd) {
        return;
      }
      const offlineData = {
        // planNo: this.formData.planNo || "", // 计划号
        batchNo: this.formData.batchNo, // 批次号
        // steelGradeName: this.formData.steelGradeName || "", // 钢种
        // prodSpec: this.formData.prodSpec || "", // 规格
        furnaceNo: this.formData.furnaceNo, // 炉次号

        // batchBegin: this.formData.batchBegin || "", // 入炉时间
        batchEnd: this.formData.furnaceBatchOut || "", // 出炉时间
        // furnaceBegin: this.formData.furnaceBegin || "", // 点火时间
        furnaceEnd: this.formData.furnaceBatchEnd || "", // 停火时间
      };

      // 调用下线API
      const response = await ZgRecordFurnaceApi.offlineJrRecord(offlineData);
      if (response.code === 0) {
        uni.showToast({
          title: "加热炉出炉记录更新成功",
          icon: "success",
        });
      } else {
        uni.showToast({
          title: "加热炉出炉记录更新失败",
          icon: "none",
        });
      }
    },
    async updateTFurnaceOut() {
      // 调用更新退火炉出炉的方法
      // 构建下线数据
      //判断出炉时间停火时间是否为空,增加判断 批次号是否为空
      if (
        !this.formData.tFurnaceBatchBegin &&
        !this.formData.tFurnaceBatchEnd
      ) {
        return;
      }
      //弹出对话框，显示轧制记录：批次号、钢种、创建日期，默认全选
      //查询条件为：当天、退火炉开始时间或结束时间不为空的数据
      //将选中的记录进行更新退火炉的开始和结束时间，调用更新轧制实际。

      try {
        // 获取当前日期时间范围（支持时分秒）
        const currentDate = this.formData.currentDate;

        // 构建当天的开始和结束时间（包含时分秒）
        const startOfDay = currentDate + " 00:00:00";
        const endOfDay = currentDate + " 23:59:59";

        // 查询条件：当天时间范围、退火炉开始时间或结束时间不为空的数据
        const queryParams = {
          ywDate: [startOfDay, endOfDay], // 使用数组格式传递时间范围
          processName: this.formData.processName,
          pageNo: 1,
          pageSize: 100,
        };

        // 调用查询轧制记录API
        const response = await ZgRecordRollApi.getZgRecordRollPage(queryParams);

        if (
          response.code !== 0 ||
          !response.data ||
          !response.data.list ||
          response.data.list.length === 0
        ) {
          uni.showToast({
            title: "未找到符合条件的轧制记录",
            icon: "none",
          });
          return;
        }

        const records = response.data.list;

        // 将查询结果保存到furnaceRecords
        this.furnaceRecords = records;
        this.showRecordTable = true;

        // 重置选中记录
        this.selectedRecords = [];
      } catch (error) {
        console.error("查询退火炉记录失败:", error);
        uni.showToast({
          title: "查询记录失败，请重试",
          icon: "none",
        });
      }
    },

    // 批量更新记录
    async batchUpdateRecords(selectedRecords) {
      if (!selectedRecords || selectedRecords.length === 0) {
        uni.showToast({
          title: "请选择要更新的记录",
          icon: "none",
        });
        return;
      }

      try {
        // 获取当前表单中的退火炉时间
        const tFurnaceBatchBegin = this.formData.tFurnaceBatchBegin;
        const tFurnaceBatchEnd = this.formData.tFurnaceBatchEnd;

        // 构建更新数据
        const updateData = {
          reserveVarchar1: tFurnaceBatchBegin,
          reserveVarchar2: tFurnaceBatchEnd,
        };

        // 批量更新每条记录
        for (const record of selectedRecords) {
          const params = {
            ...updateData,
            id: record.id,
          };

          // 调用正确的API方法更新轧制记录
          const res = await ZgRecordRollApi.updateZgRecordRoll(params);
          if (res.code !== 0) {
            throw new Error(`更新记录 ${record.batchNo} 失败`);
          }
        }

        // 刷新数据列表
        await this.loadPlanList();
      } catch (error) {
        console.error("批量更新记录失败:", error);
        throw error;
      }
    },

    // 将日期时间字符串转换为选择器索引
    dateTimeStringToIndex(dateTimeStr) {
      const startYear = 2020; // 与时间选择器range定义保持一致

      if (!dateTimeStr) {
        const now = new Date();
        return [
          now.getFullYear() - startYear, // 年份索引（相对于起始年份）
          now.getMonth(), // 月份索引（0-11）
          now.getDate() - 1, // 日期索引（0-30）
          now.getHours(), // 小时索引（0-23）
          now.getMinutes(), // 分钟索引（0-59）
          now.getSeconds(), // 秒索引（0-59）
        ];
      }

      try {
        const [datePart, timePart] = dateTimeStr.split(" ");
        const [year, month, day] = datePart.split("-").map(Number);
        const [hours, minutes, seconds] = timePart.split(":").map(Number);

        return [
          year - startYear, // 年份索引
          month - 1, // 月份索引（0-11）
          day - 1, // 日期索引（0-30）
          hours, // 小时索引（0-23）
          minutes, // 分钟索引（0-59）
          seconds, // 秒索引（0-59）
        ];
      } catch (error) {
        console.error("日期时间转换失败:", error);
        const now = new Date();
        return [
          now.getFullYear() - startYear,
          now.getMonth(),
          now.getDate() - 1,
          now.getHours(),
          now.getMinutes(),
          now.getSeconds(),
        ];
      }
    },

    // 将选择器索引转换为日期时间字符串
    indexToDateTimeString(indexes) {
      const [
        yearIndex,
        monthIndex,
        dayIndex,
        hourIndex,
        minuteIndex,
        secondIndex,
      ] = indexes;
      const startYear = 2020; // 与时间选择器range定义保持一致

      const year = startYear + yearIndex;
      const month = String(monthIndex + 1).padStart(2, "0");
      const day = String(dayIndex + 1).padStart(2, "0");
      const hour = String(hourIndex).padStart(2, "0");
      const minute = String(minuteIndex).padStart(2, "0");
      const second = String(secondIndex).padStart(2, "0");

      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },

    // 将时间戳（毫秒）或日期时间字符串转换为日期时间字符串 YYYY-MM-DD HH:mm:ss
    timestampToDateTimeString(timestamp) {
      if (!timestamp) {
        return "";
      }
      try {
        // 如果已经是日期时间字符串格式 YYYY-MM-DD HH:mm:ss，直接返回
        if (typeof timestamp === 'string' && timestamp.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/)) {
          return timestamp;
        }
        
        // 如果是时间戳（可能是数字或字符串格式），转换为日期时间字符串
        const date = new Date(timestamp);
        // 检查日期是否有效
        if (isNaN(date.getTime())) {
          console.error("无效的时间戳:", timestamp);
          return "";
        }
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        const seconds = String(date.getSeconds()).padStart(2, "0");
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      } catch (error) {
        console.error("时间戳转换失败:", error);
        return "";
      }
    },

    // 处理开渣时间选择变化
    handleBatchBeginChange(e) {
      const indexes = e.detail.value;
      this.batchBeginPickerIndex = indexes;
      this.formData.batchBegin = this.indexToDateTimeString(indexes);
    },

    // 处理终轧时间选择变化
    handleBatchEndChange(e) {
      const indexes = e.detail.value;
      this.batchEndPickerIndex = indexes;
      this.formData.furnaceBatchOut = this.indexToDateTimeString(indexes);
      
      // 如果开轧时间为空，则默认将开轧时间设置为出炉时间
      if (!this.formData.batchBegin) {
        this.formData.batchBegin = this.formData.furnaceBatchOut;
        this.batchBeginPickerIndex = indexes;
      }
    },

    // 处理点火时间选择变化
    handleFurnaceBeginChange(e) {
      const indexes = e.detail.value;
      this.furnaceBeginPickerIndex = indexes;
      this.formData.furnaceBatchOut = this.indexToDateTimeString(indexes);
    },

    // 处理停火时间选择变化
    handleFurnaceEndChange(e) {
      const indexes = e.detail.value;
      this.furnaceEndPickerIndex = indexes;
      this.formData.furnaceBatchEnd = this.indexToDateTimeString(indexes);
    },

    // 处理退火入炉时间选择变化
    handleTFurnaceBatchBeginChange(e) {
      const indexes = e.detail.value;
      this.tFurnaceBatchBeginPickerIndex = indexes;
      this.formData.tFurnaceBatchBegin = this.indexToDateTimeString(indexes);
      // 检查是否需要更新退火炉记录
      // this.updateTFurnaceOut();
    },

    // 处理退火出炉时间选择变化
    handleTFurnaceBatchEndChange(e) {
      const indexes = e.detail.value;
      this.tFurnaceBatchEndPickerIndex = indexes;
      this.formData.tFurnaceBatchEnd = this.indexToDateTimeString(indexes);
      // 检查是否需要更新退火炉记录
      // this.updateTFurnaceOut();
    },

    // 关闭记录选择表格
    closeRecordTable() {
      this.showRecordTable = false;
      this.selectedRecords = [];
    },

    // 处理记录选择确认
    async handleRecordSelectionConfirm(selectedRecords) {
      try {
        // 显示加载提示
        uni.showLoading({
          title: "正在更新...",
        });

        // 批量更新记录
        await this.batchUpdateRecords(selectedRecords);

        // 关闭弹窗
        this.showRecordTable = false;

        // 显示成功提示
        uni.showToast({
          title: "更新成功",
          icon: "success",
        });
      } catch (error) {
        console.error("更新失败:", error);
        uni.showToast({
          title: "更新失败，请重试",
          icon: "none",
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 确认记录选择并执行批量更新
    async confirmRecordSelection() {
      if (this.selectedRecords.length === 0) {
        uni.showToast({
          title: "请至少选择一条记录",
          icon: "none",
        });
        return;
      }

      // 过滤出选中的记录
      const selectedRecords = this.furnaceRecords.filter((record) =>
        this.selectedRecords.includes(record.id)
      );

      if (selectedRecords.length === 0) {
        uni.showToast({
          title: "未找到选中的记录",
          icon: "none",
        });
        return;
      }

      // 显示确认对话框
      uni.showModal({
        title: "确认更新",
        content: `确定要更新选中的 ${selectedRecords.length} 条记录吗？`,
        success: async (res) => {
          if (res.confirm) {
            // 关闭表格弹窗
            this.closeRecordTable();

            // 执行批量更新
            await this.batchUpdateRecords(selectedRecords);
          }
        },
      });
    },

    // 重置表单
    handleReset() {
      this.formData = {
        currentDate: dateHelperApi.getCurrentDate(),
        processCode: this.formData.processCode,
        processName: this.formData.processName,

        searchForm: {
          searchCode: "",
        },
        // 基础字段
        furnaceNo: "",
        operationMemo: "",
        workStaff: "",
        // 投料作业字段
        costWg: "",
        costCount: "",
        // 产出作业字段
        batchNo: "",
        qaWg: "",
        qaCount: "",
        scrapCount: "",
        scrapWg: "",
        scrapReason: "",
        // 时间相关字段
        costMeth: "",
        batchBegin: "",
        batchEnd: "",
        furnaceBegin: "",
        furnaceEnd: "",
        furnaceBatchOut: "",
        furnaceBatchEnd: "",
        tFurnaceBatchBegin: "",
        tFurnaceBatchEnd: "",

        //清空投料表格
        furnaceTable: [],
        //清空查询条件
        batchNo: "",
        steelGradeName: "",
        prodSpec: "",
      };
      uni.showToast({
        title: "表单已重置",
        icon: "success",
      });
    },

    // 下线
    async handleOffline() {
      if (!this.formData.batchNo) {
        uni.showToast({
          title: "请先选择批次号",
          icon: "none",
        });
        return;
      }

      // 校验必要字段
      if (!this.formData.furnaceNo) {
        uni.showToast({
          title: "请先选择炉次号",
          icon: "none",
        });
        return;
      }

      uni.showModal({
        title: "确认保存",
        content: `确定要将批次号 ${this.formData.batchNo} 保存吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              // 构建下线数据
              const offlineData = {
                planNo: this.formData.planNo || "", // 计划号
                batchNo: this.formData.batchNo, // 批次号
                steelGradeName: this.formData.steelGradeName || "", // 钢种
                prodSpec: this.formData.prodSpec || "", // 规格
                furnaceNo: this.formData.furnaceNo, // 炉次号
                qmAmount: Number(this.formData.qmAmount) || 0, // 钢棒重量
                qmCount: Number(this.formData.qmCount) || 0, // 产出支数

                scrapCount: Number(this.formData.scrapCount) || 0, // 废品数量
                scrapWg: Number(this.formData.scrapWg) || 0, // 废品重量
                ywDate: this.formData.currentDate || "", // 业务日期
                processName: this.formData.processName, // 工序名称
                workShift: this.$store.state.user.userConfig?.workShift || "", // 班次
                wortkType: this.$store.state.user.userConfig?.workClass || "", // 班别
                workStaff: this.formData.workStaff || "", // 操作工
                busMemo: this.formData.busMemo || "", // 备注
                batchBegin: this.formData.batchBegin || "", // 入炉时间
                batchEnd: this.formData.furnaceBatchOut || "", // 出炉时间
                furnaceBatchOut: this.formData.furnaceBatchOut || "", // 加热炉出炉时间
                furnaceBatchEnd: this.formData.furnaceBatchEnd || "", // 加热炉停火时间
                tFurnaceBatchBegin: this.formData.tFurnaceBatchBegin || "", // 退火入炉时间
                tFurnaceBatchEnd: this.formData.tFurnaceBatchEnd || "", // 退火出炉时间
              };
              console.log("offlineData:", offlineData);

              // 调用下线API
              const response = await ZgRecordRollApi.offlineZzRecord(
                offlineData
              );

              if (response.code === 0) {
                uni.showToast({
                  title: "保存成功",
                  icon: "success",
                });

                // 成功后重置表单
                this.handleReset();
              } else {
                uni.showToast({
                  title: response.msg || "保存失败",
                  icon: "none",
                });
              }
            } catch (error) {
              console.error("下线处理失败:", error);
              uni.showToast({
                title: "保存失败，请重试",
                icon: "none",
              });
            }
          }
        },
      });
    },
  },
};
</script>

<style lang="scss">
@import "~@/pages/smart/scss/create.scss";

// picker组件样式
.form-picker {
  flex: 1;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  padding: 8px;
  background-color: #fafafa;
  cursor: pointer;

  .picker-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .picker-arrow {
      color: #999;
      font-size: 12px;
    }

    .btn-confirm-time {
      background-color: #1890ff;
      color: white;
      border: none;
      border-radius: 4px;
      padding: 8px 12px;
      font-size: 12px;
      white-space: nowrap;
      cursor: pointer;
      transition: background-color 0.3s;
    }

    .btn-confirm-time:hover {
      background-color: #40a9ff;
    }

    .btn-confirm-time:active {
      background-color: #096dd9;
    }
  }
}
</style>
